// 初始化数据处理
import Util from "@/js_sdk/validator/util.js"
	import { areaPower  } from "@/js_sdk/manage-area/manage.js";
const db = uniCloud.database()
let startTime = Util.getDayTimestamps(0).startTime ;
let endTime = Util.getDayTimestamps(0).endTime ;

// 初始化订单函数
async function initOrder() {
	  try {
		 // 查询订单总量
		 const $ = db.command.aggregate
		 const dbCmd = db.command
		 const orderCountData = await  db.collection('orders').aggregate()
			.lookup({
				from: 'shop',
				let: { shopId:"$shop_id",areaS:"05300103" },
				pipeline: $.pipeline()
				.match(dbCmd.expr(
					$.and([
						$.eq(['$_id', '$$shopId']),
					])
				))
				.done(),
				as: 'shopInfo'
			})
			.match({
			 "status.value": { $gte: 2, $lte: 5 },
			 "shopInfo.area_all.value":dbCmd.in( areaPower() ) ,
			})
			.count('count')
			.end()
			let orderCount = 0;
			if(orderCountData.result.data.length > 0){
				orderCount = orderCountData.result.data[0].count
			}
			
		 // 查询今日订单总量和昨日订单总量
		 let order = db.collection('orders').field("create_date,status,shop_id").orderBy("create_date.time_stamp desc").getTemp()
		 let shop = db.collection('shop').field("_id,title,tel,area_all").getTemp({getOne: true})
		const orderData = await db.collection(order, shop).where({
		 	"create_date.time_stamp": db.command.gt(Util.getDayTimestamps(1).startTime).and(db.command.lt(Util.getDayTimestamps(0).endTime)),
		 	"shop_id.area_all.value":db.command.in( areaPower() ),
		 	"status.value": db.command.gte(1)
		 }).get()
		 let dayNumber = 0;
		 let yesterday = 0;
		 orderData.result.data.forEach(item => {
			if (item.create_date.time_stamp > startTime && item.create_date.time_stamp < startTime + 86400000) {
			  dayNumber += 1;
			}
			if (item.create_date.time_stamp < (endTime - 86400000) ) {
				yesterday += 1;
			}
		 });
		 return {
				title:'订单量统计',lable:"单量总计",
				number: orderCount,
				icon:'wallet-filled',color:'rgb(243, 104, 224)',background:'rgba(243, 104, 224,.2)',
				dayNumber,yesterday
		 };
	  } catch (error) {
			console.error("初始化订单时出错：", error);
			throw error;
	  }
}

async function initUser(){
	try {
		const userQuery = await db.collection("uni-id-users").field("_id,register_date").orderBy("register_date desc").limit(999).get({getOne:false,getCount:true})
	// 今日用户
		const today = await db.collection("uni-id-users")
			.where({"register_date": db.command.gt(Util.getDayTimestamps(0).startTime).and( db.command.lt(Util.getDayTimestamps(0).endTime ) )})
		.field("_id").get({getOne:false,getCount:true})
	// 昨日用户
		const yesterday = await db.collection("uni-id-users")
			.where({"register_date": db.command.gt(Util.getDayTimestamps(1).startTime).and( db.command.lt(Util.getDayTimestamps(1).endTime ) )})
		.field("_id").get({getOne:false,getCount:true})
		return {
			title:'用户量统计',lable:"用户总数",
			number:userQuery.result.count,
			dayNumber:today.result.count,
			icon:'person-filled',color:'rgb(23, 192, 235)',background:'rgba(23, 192, 235,.2)',
			yesterday:yesterday.result.count
		}
	}catch(error){
		console.error("初始化订单时出错：", error);
		throw error;
	}
}
async function initAreaBill(){
	try {
		// 聚合查询订单
		const $ = db.command.aggregate
		const dbCmd = db.command
		const polymerization = await  db.collection('orders').aggregate()
		.lookup({
			from: 'shop',
			let: { shopId:"$shop_id",areaS:"05300103" },
			pipeline: $.pipeline()
			.match(dbCmd.expr(
				$.and([
					$.eq(['$_id', '$$shopId']),
				])
			)).done(),
			as: 'shopInfo'
		})
		.match({
			"status.value": dbCmd.gt(1).and(dbCmd.lt(9)),
			"shopInfo.area_all.value":dbCmd.in( areaPower() ) ,
		})
		.group({
		  _id: null,
		  count:$.sum(1),
		  deliveryPrice:$.sum("$delivery_price"),
		  platformCommission:$.sum("$platform_commission")
		}).end()
		let delivery = {dayNumber:0, yesterday:0, };
		let platform = {dayNumber:0, yesterday:0, };
		let orderCount = {dayNumber:0, yesterday:0, };
		if(polymerization.result.data.length > 0){
			delivery.number = ( polymerization.result.data[0].deliveryPrice / 100).toFixed(2);
			platform.number =	( polymerization.result.data[0].platformCommission / 100).toFixed(2);
			orderCount.number = polymerization.result.data[0].count
		}
		// 查询今日订单总量和昨日订单总量
		 let order = db.collection('orders').field("create_date,status,shop_id,delivery_price,platform_commission").orderBy("create_date.time_stamp desc").getTemp()
		 let shop = db.collection('shop').field("_id,title,tel,area_all").getTemp({getOne: true})
		const orderData = await db.collection(order, shop).where({
		 	"create_date.time_stamp": db.command.gt(Util.getDayTimestamps(1).startTime).and(db.command.lt(Util.getDayTimestamps(0).endTime)),
		 	"shop_id.area_all.value":db.command.in( areaPower() ),
		 	"status.value": db.command.gte(1)
		 }).get()
		 
		 orderData.result.data.forEach(item => {
			if (item.create_date.time_stamp > startTime && item.create_date.time_stamp < startTime + 86400000) {
				delivery.dayNumber += parseFloat( (item.delivery_price / 100).toFixed(2) ) ;
				platform.dayNumber += parseFloat( (item.platform_commission / 100).toFixed(2) ) ;
				orderCount.dayNumber += 1;
			}
			if (item.create_date.time_stamp < (endTime - 86400000) ) {
				delivery.yesterday +=  parseFloat( (item.delivery_price / 100).toFixed(2) ) ;
				platform.yesterday +=  parseFloat( (item.platform_commission / 100).toFixed(2) ) ;
				orderCount.yesterday += 1;
			}
		 });
		return {
			orderCount:{
				title:'订单量统计',
				lable:"单量总计",
				number:orderCount.number,
				dayNumber:orderCount.dayNumber,
				yesterday:orderCount.yesterday,
				icon:'wallet-filled',color:'rgb(243, 104, 224)',background:'rgba(243, 104, 224,.2)',
			},
			delivery:{
				title:'配送费',
				lable:"配送费(￥)",
				number:delivery.number,
				dayNumber:delivery.dayNumber,
				yesterday:delivery.yesterday,
				icon:'fire-filled',color:'rgb(255, 221, 89)',background:'rgba(255, 221, 89,.2)',
			},
			platform:{
				title:'平台佣金',
				lable:"佣金总计(￥)",
				number:platform.number,
				dayNumber:platform.dayNumber ,
				yesterday:platform.yesterday,
				icon:'person-filled',color:'rgb(23, 192, 235)',background:'rgba(23, 192, 235,.2)',
			}
		}
	}catch(error){
		console.error("初始化订单时出错：", error);
		throw error;
	}
}
// 导出模块
export {
  // 订单
  initOrder,
  // 用户总数
  initUser,
  // 访问总数
  initAreaBill
};
